'''
@Project ：my_python_project 
@File    ：生成器表达式.py
@IDE     ：PyCharm 
@Author  ：xionglinhui
@Date    ：2024/8/22 上午9:10 
'''

# 4、生成器表达式

# g = (i for i in range(4))
#
# print(g) # 得到一个生成器对象，<generator object <genexpr> at 0x7f1766c90660>
#
# print(g.__next__()) # 0
# print(g.__next__()) # 1
# print(next(g))      # 2
# print(next(g))      # 3
# # print(next(g))      # 抛出异常StopIteration

# 对比列表生成式，生成器表达式的优点自然是节省内存（一次只产生一个值在内存中）

with open('aaa.txt', mode='rt',encoding='utf-8') as f:
# # 方式一：常规写法
    res=0
    for line in f:
        res+=len(line)
    print(f'方式一:{res}')

    with open('aaa.txt', mode='rt',encoding='utf-8') as f:
# # 方式二：使用列表表达式
    res1 = 0
    res1 = sum([len(line) for line in f])
    print(f'方式二:{res1}')

with open('aaa.txt', mode='rt',encoding='utf-8') as f:
# # 方式三：使用生成器表达式
    res2 = 0
    res2 = sum((len(line) for line in f))
    print(f'方式三:{res2}')


sum(1,2,3,4,5)